package com.wd.tw.utils;

import com.digitalpetri.modbus.codec.Modbus;
import com.digitalpetri.modbus.master.ModbusTcpMaster;
import com.digitalpetri.modbus.master.ModbusTcpMasterConfig;
import com.digitalpetri.modbus.requests.WriteSingleRegisterRequest;
import com.digitalpetri.modbus.responses.WriteSingleRegisterResponse;
import io.netty.util.ReferenceCountUtil;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ModbusMasterTcpWriter {
    static ModbusTcpMaster writeMaster;

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        initModbusMasterTcp();
        writeHoldingRegisters(0, 12, 1);
        release();
    }

    // 初始化
    public static void initModbusMasterTcp(){
        // 创建匹配，添加信息
        ModbusTcpMasterConfig writeTcpMasterConfig = new ModbusTcpMasterConfig
                .Builder("192.168.100.204")
                .setPort(503)
                .build();
        writeMaster = new ModbusTcpMaster(writeTcpMasterConfig);
        writeMaster.connect();
    }

    public static Number writeHoldingRegisters(int serverAddress, int value, int unitId) throws ExecutionException, InterruptedException {
        Number result = null;
        CompletableFuture<WriteSingleRegisterResponse> future = writeMaster
                .sendRequest(new WriteSingleRegisterRequest(serverAddress, value), unitId);
        WriteSingleRegisterResponse response = future.get();
        if (response != null){
            result = response.getValue();
            ReferenceCountUtil.release(response);
        }
        return result;
    }
    // 释放资源
    public static void release(){
        if (writeMaster != null){
            writeMaster.disconnect();
        }
        Modbus.releaseSharedResources();
    }
}
